const path = require('path')
const fs = require('fs')
const Router = require('koa-router')
const uuidv4 = require('uuid/v4')

const { Auth } = require('../../middlewares/auth')
const { fileDisplay } = require('../../core/tinify')
const { getFolderPath } = require('../../core/folder')

const router = new Router({
    prefix: '/api/v1'
})


/**
* @api {post} /api/v1/upload/image 图片上传
* @apiGroup file
* @apiVersion 1.0.0
* @apiParam {FormData} file 参数
*
* @apiSuccess (success){String} validatorMsg 验证消息
* @apiSuccess (success){String} msg 返回消息
* @apiSuccess (success){Object} data 返回数据
* @apiSuccess (success){Int} errCode 状态码
* @apiSuccess (success){String} method 请求方式
* @apiSuccess (success){String} path 路径
* @apiSuccess (success){String} token 登录凭证
* @apiSuccess (success){String} url 返回成功地址需前端自己加上服务器前缀和端口号
*
* @apiSuccessExample {json} 成功:
* {
*   "validatorMsg": [],
*   "msg": "", // 成功信息
*   "data": {},
*   "errCode": 0, // 状态码
*   "method": "", // 请求方式
*   "path": "" // 路径
* }
*
* @apiError (error){Array} validatorMsg 验证消息
* @apiError (error){String} msg 返回消息
* @apiError (error){Null} data 返回数据
* @apiError (error){Int} errCode 状态码
* @apiError (error){String} method 请求方式
* @apiError (error){String} path 路径
*
* @apiErrorExample {json} 失败:
* {
*   "validatorMsg": [],
*   "msg": "", //错误信息
*   "data": null,
*   "errCode": 10000 //状态码,
*   "method": "", // 请求方式
*   "path": "" // 路径
* }
*/
router.post('/upload/image',  async (ctx, next) => {

    const file = ctx.request.files.file // 获取上传文件
    const fileFormat = (file.name).split(".")

    // 过滤上传的文件
    let Suffix = ['jpg', 'JPG', 'bmp', 'BMP', 'jpeg', 'JPEG', 'png', 'PNG', 'gif', 'GIF']

    if (Suffix.includes(fileFormat[fileFormat.length - 1].split('.').splice(-1)[0])) {

        
        const fileName = uuidv4() + '_' + Date.now() + "." + fileFormat[fileFormat.length - 1]
        
        // 创建可读流
        const reader = await fs.createReadStream(file.path)
        const filePath = await getFolderPath('uploadImage')

        // 创建可写流
        const upStream = await fs.createWriteStream(path.join(filePath.folderPath, fileName))

        // 可读流通过管道写入可写流
        reader.pipe(upStream)

        const data = {
            url: path.join(filePath.staticPath, fileName)
        }

        throw new global.errs.Success(data)
            

    } else {

        throw new global.errs.fileUploadError()

    }
  
})

/**
* @api {post} /api/v1/upload/images 多图片上传
* @apiGroup file
* @apiVersion 1.0.0
* @apiParam {FormData} file 参数
*
* @apiSuccess (success){String} validatorMsg 验证消息
* @apiSuccess (success){String} msg 返回消息
* @apiSuccess (success){Object} data 返回数据
* @apiSuccess (success){Int} errCode 状态码
* @apiSuccess (success){String} method 请求方式
* @apiSuccess (success){String} path 路径
* @apiSuccess (success){String} token 登录凭证
* @apiSuccess (success){String} url 返回成功地址需前端自己加上服务器前缀和端口号
*
* @apiSuccessExample {json} 成功:
* {
*   "validatorMsg": [],
*   "msg": "", // 成功信息
*   "data": {},
*   "errCode": 0, // 状态码
*   "method": "", // 请求方式
*   "path": "" // 路径
* }
*
* @apiError (error){Array} validatorMsg 验证消息
* @apiError (error){String} msg 返回消息
* @apiError (error){Null} data 返回数据
* @apiError (error){Int} errCode 状态码
* @apiError (error){String} method 请求方式
* @apiError (error){String} path 路径
*
* @apiErrorExample {json} 失败:
* {
*   "validatorMsg": [],
*   "msg": "", //错误信息
*   "data": null,
*   "errCode": 10000 //状态码,
*   "method": "", // 请求方式
*   "path": "" // 路径
* }
*/
router.post('/upload/images', new Auth().m, async (ctx, next) => {
    
    const files = ctx.request.files.file // 获取上传文件
    // 过滤上传的文件
    const Suffix = ['jpg', 'JPG', 'bmp', 'BMP', 'jpeg', 'JPEG', 'png', 'PNG', 'gif', 'GIF']

    let fileArr = []
    for (let file of files) {
        
        let fileFormat = (file.name).split(".")

        if (Suffix.includes(fileFormat[fileFormat.length - 1].split('.').splice(-1)[0])) {
            let fileName = uuidv4() + '_' + Date.now() + "." + fileFormat[fileFormat.length - 1]

            // 创建可读流
            let reader = await fs.createReadStream(file.path)
            let filePath = await await getFolderPath('uploadImage')

            // 创建可写流
            let upStream = await fs.createWriteStream(path.join(filePath.folderPath, fileName))
            // 可读流通过管道写入可写流
            await reader.pipe(upStream)

            fileArr.push(path.join(filePath.staticPath, fileName))

        }

    }

    if (fileArr.length) {
        throw new global.errs.Success(fileArr)
    } else {
        throw new global.errs.fileUploadError()
    }
  
})

router.get('/upload/tinifyFiles', async (ctx, next) => {
    
    // 解析需要遍历的文件夹
    let filePathInput = await path.resolve(`${process.cwd()}/static/unTinify`)
    
    // 解析后的文件夹
    let filePathOutput = await path.resolve(`${process.cwd()}/static/uploadImage`)
    fileDisplay(filePathInput, filePathOutput)

})


module.exports = router
